from flask import Flask, request, jsonify
import os
from datetime import datetime
# 从 models 导入 db 和所有模型（关键）
from models import db, User, ImageUpload, Task
from flask_cors import CORS

# 初始化 Flask 应用
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 绑定 db 到 app
db.init_app(app)

# 创建上传目录
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# 在应用上下文中初始化数据库和测试用户
with app.app_context():
    db.create_all()  # 创建所有表
    # 检查是否有用户，没有则创建
    if not User.query.first():
        test_user = User(
            username="test",
            email="test@example.com",
            password_hash="hashed_password"
        )
        db.session.add(test_user)
        db.session.commit()

# 导入 Celery 相关（放在最后）
from celery_app import app as celery_app
from tasks import process_image

# 上传接口
@app.route('/upload', methods=['POST'])
def upload_image():
    if 'image' not in request.files:
        return jsonify({"error": "未上传图片"}), 400
    file = request.files['image']
    if file.filename == '':
        return jsonify({"error": "未选择图片"}), 400

    try:
        filename = file.filename
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)
        file_size = os.path.getsize(file_path) / 1024
    except Exception as e:
        return jsonify({"error": f"保存图片失败：{str(e)}"}), 500

    # 获取测试用户
    user = User.query.first()
    if not user:
        return jsonify({"error": "用户不存在"}), 401

    # 创建图片记录
    image_upload = ImageUpload(
        filename=filename,
        file_path=file_path,
        file_size=file_size,
        user_id=user.id
    )
    db.session.add(image_upload)
    db.session.commit()

    # 创建任务记录
    task = Task(
        celery_task_id="",
        task_type="image_process",
        status="PENDING",
        user_id=user.id,
        image_id=image_upload.id
    )
    db.session.add(task)
    db.session.commit()

    # 触发异步任务
    celery_result = process_image.delay(image_upload.id)
    task.celery_task_id = celery_result.id
    db.session.commit()

    return jsonify({
        "message": "图片上传成功，任务已启动",
        "task_id": celery_result.id,
        "image_id": image_upload.id
    }), 200
CORS(app)
if __name__ == '__main__':
    app.run(debug=True)